package chapter11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-22 下午4:23
 */
public class FileWriterTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileWriterTest.class);

    public static void main(String[] args) {
        File file = new File(File.separator + "home" + File.separator + "lzy" + File.separator + "logs" + File.separator + "test" + File.separator + "test.dat");

        if (!file.getParentFile().exists()) {
            LOGGER.info("create directory {}:{}", file.getParent(), file.getParentFile().mkdirs());
        }

        try (FileWriter writer = new FileWriter(file, true)) {
            String str = "this is write with file writer.\n\r";
            writer.append(str);
        } catch (IOException e) {
            e.printStackTrace();
        }

        StringBuilder builder = new StringBuilder();

        try (FileReader reader = new FileReader(file)) {
            int len = 0;
            char[] dat = new char[30];
            while ((len = reader.read(dat)) != -1) {
                builder.append(new String(dat, 0, len));
            }
            LOGGER.info("[read]:{}", builder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
